﻿using Puman;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace LAB.Manager
{

    public static class UserManager
    {
        public delegate void handler(t_user user);
        public static event handler afterInsert;
        public static event handler afterLogin;
        public static event handler afterChangePwd;

        static UserManager()
        {
            // 注册后发送确认邮件
            afterInsert += (user) =>
            {
                sendVerifyMail(user.id);
            };

            afterLogin += (user) =>
            {

            };
        }



        #region 注册

        public static int Insert(string userName, string password)
        {
            int rst = -1;
            using (var db = new TagerEntities())
            {
                // 重名问题

                if (checkUser(db, userName))
                {
                    return -2;
                }

                t_user user = new t_user() { userName = userName, pwd = password, status = 0, dt = DateTime.Now };

                db.t_user.Add(user);
                db.SaveChanges();

                rst = 0;

                if (afterInsert != null)
                {
                    afterInsert(user);
                }


            }
            return rst;
        }
        #endregion
        #region 邮箱绑定验证
        #endregion
        #region 登录
        public static t_user Login(string userName, string pwd)
        {
            t_user rst = null;
            using (var db = new TagerEntities())
            {
                t_user user = db.t_user.FirstOrDefault(c => c.userName == userName && c.pwd == pwd && c.status == 1);
                if (user == null)
                {
                    return null;
                }
                rst = user;
                if (afterLogin != null)
                {
                    afterLogin(user);
                }


            }
            return rst;
        }
        #endregion



        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="exPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        public static int ChangePassword(int userId, string exPassword, string newPassword)
        {
            int rst = -1;
            using (var db = new TagerEntities())
            {


                t_user user = db.t_user.FirstOrDefault(c => c.id == userId);
                if (user == null)
                {
                    return -2;
                }
                if (user.pwd != exPassword)
                {
                    return -3;
                }
                user.pwd = newPassword;
                db.SaveChanges();
                rst = 0;

                if (afterChangePwd != null)
                {
                    afterChangePwd(user);
                }
            }
            return rst;
        }
        #endregion


        #region 重置密码
        public static int resetPwd(int userId, string pwd)
        {
            int rst = -1;
            using (var db = new TagerEntities())
            {
                var user = db.t_user.FirstOrDefault(c => c.id == userId);
                if (user == null)
                {
                    return -2;
                }
                user.pwd = pwd;
                db.SaveChanges();

                if (afterChangePwd != null)
                {
                    afterChangePwd(user);
                }
            }
            return rst;
        }

        #endregion


        #region 发送邮件
        public static int sendVerifyMail(int userId)
        {
            int rst = -1;
            using (var db = new TagerEntities())
            {
                t_user user = db.t_user.FirstOrDefault(c => c.id == userId);
                if (user == null)
                {
                    return -2;
                }
                if (user.status != 0)
                {
                    return -3;
                }
                string urlContent;
                string verifyPage = ConfigurationManager.AppSettings["verifyPage"];
                string userIdStr = userId.ToString();
                string md5Key = ConfigurationManager.AppSettings["md5Key"];

                Dictionary<string, string> dicParam = new Dictionary<string, string>();
                dicParam.Add("userId", userId.ToString());
                dicParam.Add("dt", DateTime.Now.ToString("yyyy/MM/dd"));

                urlContent = verifyPage + "?" + Encrypt.toUrl(dicParam, md5Key);
                Mailer.Send(user.userName, urlContent);

            }
            return rst;
        }
        #endregion

        #region 验证通过
        public static int verify(int userId)
        {
            int rst = -1;
            using (var db = new TagerEntities())
            {
                t_user user = db.t_user.FirstOrDefault(c => c.id == userId);
                if (user == null)
                {
                    return -2;
                }
                if (user.status == 1)
                {
                    return -3;
                }
                user.status = 1;
                db.SaveChanges();
                rst = 0;
            }
            return rst;
        }

        public static int verify(int userId, DateTime dt, string md5Code)
        {
            int rst = -1;
            int min = int.Parse(ConfigurationManager.AppSettings["verifyInterval"]);
            if ((DateTime.Now - dt) > new TimeSpan(min, 0, 0))
            {
                return -9;
            }
            Dictionary<string, string> dicParam = new Dictionary<string, string>();
            dicParam.Add("userId", userId.ToString());
            dicParam.Add("dt", dt.ToString("yyyy/MM/dd"));
            string md5Key = ConfigurationManager.AppSettings["md5Key"];
            if (!Encrypt.equal(dicParam, md5Key, md5Code))
            {
                return -8;
            }
            rst = verify(userId);
            return rst;
        }

        #endregion




        #region HELP
        /// <summary>
        /// 获取一个8位的随机数
        /// </summary>
        /// <returns></returns>
        static String GetRadom()
        {
            StringBuilder radom = new StringBuilder(32);
            Random rand = new Random();
            for (int i = 0; i < 8; i++)
            {
                radom.Append(rand.Next(0, 10));
            }

            return radom.ToString();
        }

        #region 用户是否存在
        static bool checkUser(TagerEntities db, string userName)
        {
            return db.t_user.Any(c => c.userName == userName);
        }

        /// <summary>
        /// 是否存在该编号的用户
        /// </summary>
        /// <param name="db"></param>
        /// <param name="userId"></param>
        /// <returns>如果存在返回true</returns>
        static bool checkUser(TagerEntities db, int userId)
        {
            return db.t_user.Any(c => c.id == userId);
        }
        #endregion
        #endregion



        public static int getUserIdByUserName(string userName)
        {
            int rst = -1;
            using (var db=new TagerEntities())
            {
                t_user user = db.t_user.FirstOrDefault(c=>c.userName==userName);
                rst = user == null ? -1 : user.id;
            }
            return rst;
        }
    }
}